#练习作用域之间的转换
a=0
b=[]
def foo():
    a=2
    #b.append(2)
    #b=4
    print(b)
    return None
foo()
print(a,b)

c={}
def foo2():
    c["a"]=100
    return c
foo2()
print(c)

d=5
def foo3():
    global d
    d=10
    print(d)
foo3()
print(d)

print("--------------------------------")

def f():
    total = 0
    def fo(value):
        nonlocal total
        total +=value
        return total
    print(total)
    return fo
a=f()
print(a(6))
print(a(8))
print("----------------------------")

# 实现一个装饰器，用来输出函数的执行时间
import time
def clock_deco(func):
    def wrap(*args):
        start_time = time.time()
        result = func(*args)
        end_time = time.time()
        print(f"{func.__name__} 执行时长为：{format(end_time - start_time, '.2f')}s")
        return result
    return wrap

@clock_deco
def sum (a, b):
    s=0
    for i in range(b+1):
        s+=(a**i)
    return s

print(sum(3,5))

# 使用装饰器来为斐波那契函数增加缓存
fi = {}
def cache_deco(func):
    global fi
    def wrap(num):
        if num not in fi:
            fi[num] = func(num)
        return fi[num]
    return wrap

@cache_deco
def fib(x):
    if x < 2:
        return x
    else:
        return fib(x - 2) + fib(x - 1)

print(fib(10))
print(fib(10))
print(fi)